package com.sdrt.lums.tp.message;

import com.sdrt.lums.tp.config.RedisTemplateManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
public class SubscribeCar {

    private static final String CAR_STORAGE_PREFIX = "CAR_STORAGE";

    private static final long QUANTITY_TIME = 86400000L;


    /**
     * 新增订阅拍照车牌
     *
     * @param carPlate  车牌
     * @return  添加是否成功
     */
    public static boolean addSubscribe(String carPlate) {
        if (StringUtils.hasText(carPlate)) {
            RedisTemplateManager.getTemplate().opsForZSet().add(CAR_STORAGE_PREFIX, carPlate, System.currentTimeMillis());
            return true;
        }
        return false;
    }


    /**
     * 取消订阅/完成订阅任务
     *
     * @param carPlate  车牌
     */
    public static void cancelSubscribe(String carPlate) {
        RedisTemplateManager.getTemplate().opsForZSet().remove(CAR_STORAGE_PREFIX, carPlate);
    }


    /**
     * 检查车牌是否有效订阅
     * true:    订阅且在有效时间内订阅
     * false:   未订阅或订阅超出有效时间
     *
     * @param carPlate  车牌
     * @return  是否存在有效订阅信息
     */
    public static boolean isQuantitySubscribe(String carPlate) {
        if (StringUtils.hasText(carPlate)) {
            Double subTime = RedisTemplateManager.getTemplate().opsForZSet().score(CAR_STORAGE_PREFIX, carPlate);
            if (subTime == null) {
                return false;
            }
            return System.currentTimeMillis() - subTime <= QUANTITY_TIME;
        }
        return false;
    }


    /**
     * 清除所有超过订阅有效时间的车牌订阅记录
     */
    public static void clean() {
        RedisTemplateManager.getTemplate().opsForZSet().removeRangeByScore(CAR_STORAGE_PREFIX, 0, System.currentTimeMillis() - QUANTITY_TIME);
    }


}
